<template>
  <a-modal
    title="物流审核"
    :width="1400"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    :okButtonProps="{ props: { disabled: disableSubmit } }"
    @cancel="handleCancel"
    cancelText="关闭"
    style="top: 20px"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :md="5" :sm="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="请选择">
              <j-dict-select-tag
                v-decorator="['channelFlag', validatorRules.status]"
                @change="handleWarehouseFlag"
                :type="'radioButton'"
                :triggerChange="true"
                dictCode="OmsReturnLogisticsApprove_status"
              />
            </a-form-item>
          </a-col>
          <a-col :md="10" :sm="12">
            <a-form-item
              :hidden="model.channelFlag == '6'"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="拒绝备注">
              <a-textarea v-if="model.channelFlag != '6'" :rows="1" placeholder="请输入拒绝备注"
                          v-decorator="['note', validatorRules.note]"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="title">退货申请信息</div>
      <a-table
        style="margin-bottom: 24px"
        rowKey="id"
        bordered
        :scroll="{ x: 800 }"
        :columns="returnGoodsColumns"
        :pagination="false"
        :dataSource="returnOrderEditColumns2">
        <div slot="returnFileList" slot-scope="returnFileList, row">
          <div :key="index" v-for="(file, index) in returnFileList">
            <a :href="file.url" target="_blank">{{ file.name }}</a>
          </div>
        </div>
      </a-table>

      <div class="title">审核信息</div>
      <a-table
        size="middle"
        bordered
        :columns="goodsColumns"
        :dataSource="returnOrderEditColumns"
        :scroll="{ y: 440 }"
        :pagination="false"
        :loading="loading"
      >
        <div slot="returnUnitCountNotUnit" slot-scope="returnUnitCountNotUnit, row">
          <a-input-number
            id="inputNumber1"
            :value="returnUnitCountNotUnit"
            :min="0"
            @change="onChangeUnit($event, row)"
            :precision="0"
          />
        </div>
        <div slot="returnSkuUnitCountNotUnit" slot-scope="returnSkuUnitCountNotUnit, row">
          <a-input-number
            id="inputNumber2"
            :precision="0"
            :value="returnSkuUnitCountNotUnit"
            :min="0"
            @change="onChangeSkuUnit($event, row)"
          />
        </div>
      </a-table>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from "lodash.pick";
import {httpAction, postAction} from "@/api/manage";
import {getAction} from "@/api/manage";
import {mergeSameProducts} from '@/utils/util'

export default {
  name: "OrderReturnApplyLogisticsApprove",

  data() {
    return {
      visible: false,
      confirmLoading: false,
      disableSubmit: false,
      approveStatus: 5,
      applyId: 0,
      instructionList: [],
      form: this.$form.createForm(this),
      validatorRules: {
        status: {rules: [{required: true, message: "请选择状态!"}]},
        note: {rules: [{required: true, message: '请输入拒绝原因!'}]},
      },
      labelCol: {
        xs: {span: 24},
        sm: {span: 8},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 13},
      },
      type: 1,
      returnOrderEditColumns: [],
      returnOrderEditColumns2:[],
      goodsColumns: [
        {
          title: "商品名称",
          key: "productName",
          dataIndex: "productName",
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {},
            };
            if (row.showName) {
              obj.attrs.rowSpan = row.rowSpan;
            } else if(row.hideName){
              obj.attrs.rowSpan = 0;
            } 
           
            return obj;
          },
        },
        {
          title: "批次号",
          key: "batchNo",
          dataIndex: "batchNo",
        },
        {
          title: "物流实收（整箱）",
          key: "returnSkuUnitCountNotUnit",
          dataIndex: "returnSkuUnitCountNotUnit",
          scopedSlots: {customRender: "returnSkuUnitCountNotUnit"},
        },
        {
          title: "物流实收（零散）",
          key: "returnUnitCountNotUnit",
          dataIndex: "returnUnitCountNotUnit",
          scopedSlots: {customRender: "returnUnitCountNotUnit"},
        },
      ],
      returnGoodsColumns: [
        {
          title: '商品名称',
          key: 'productName',
          width: 150,
          dataIndex: 'productName'
        },
        {
          title: '物料编码',
          key: 'productSkuCode',
          width: 140,
          dataIndex: 'productSkuCode'
        },

        {
          title: '箱规',
          key: 'productSpecUnit',
          width: 100,
          dataIndex: 'productSpecUnit'
        },
        {
          title: '单价',
          key: 'unitPrice',
          width: 80,
          dataIndex: 'unitPrice'
        },
        {
          title: '箱装价',
          key: 'skuUnitPrice',
          width: 100,
          dataIndex: 'skuUnitPrice'
        },
        {
          title: '申请数量(整箱)',
          key: 'returnSkuUnitCount',
          width: 130,
          dataIndex: 'returnSkuUnitCount'
        },
        {
          title: '申请数量(零散)',
          key: 'returnUnitCount',
          width: 130,
          dataIndex: 'returnUnitCount'
        },
        {
          title: '数量小计',
          key: 'minUnitQuantityCount',
          width: 90,
          dataIndex: 'minUnitQuantityCount'
        },
        {
          title: '小计金额',
          key: 'totalAmount',
          width: 100,
          dataIndex: 'totalAmount'
        },
        {
          title: '申请原因',
          key: 'reason',
          width: 140,
          dataIndex: 'reason'
        },
        {
          title: '申请凭证',
          key: 'returnFileList',
          width: 140,
          dataIndex: 'returnFileList',
          scopedSlots: {customRender: "returnFileList"},
        },
      ],
      url: {
        approve: "/returns/omsOrderReturnApply/approve",
        returnOrderItem: "/returns/omsOrderReturnItem/returnOrderItem",
        returnBatchOrderItem: "/returns/omsOrderReturnItemBatch/returnBatchOrderItem",
      },
      loading: false,
    };
  },
  computed: {},
  methods: {
    show(record) {
      this.instructionList = [];
      this.visible = true;
      this.model = Object.assign({}, record);
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, "channelFlag", 'note', "reason"));
      });
      if (record != {} && record.returnCertificate!=null && record.returnCertificate.length > 0) {
        this.instructionList = eval(record.returnCertificate);
      }
      this.model.channelFlag = 6;
      this.applyId = record.id;
      if (this.applyId) {
        this.loadGoodsData();
        this.loadReturnBatchData();
      }
    },
    loadGoodsData() {
      var params = {applyId: this.applyId};
      this.loading = true;
      getAction(this.url.returnOrderItem, params).then((res) => {
        if (res.success) {
          console.log(1111111)
          this.returnOrderEditColumns2 = res.result;
        }
        if (res.code === 510) {
          this.$message.warning(res.message);
        }
        this.loading = false;
      });
    },
    loadReturnBatchData() {
      var params = {applyId: this.applyId};
      this.loading = true;
      getAction(this.url.returnBatchOrderItem, params).then((res) => {
        if (res.success) {
          console.log(1111111)
          this.returnOrderEditColumns = mergeSameProducts(res.result);
        }
        if (res.code === 510) {
          this.$message.warning(res.message);
        }
        this.loading = false;
      });
    },
    close() {
      this.form.resetFields();
      this.$emit("close");
      this.visible = false;
    },
    handleSubmit() {
      this.confirmLoading = true;
      this.approveStatus = this.model.channelFlag;
      let itemList = [];
      this.returnOrderEditColumns.forEach((row) => {
        const {returnUnitCountNotUnit, returnSkuUnitCountNotUnit, id,productId} = row;
        itemList.push({
          returnUnitCountNotUnit,
          returnSkuUnitCountNotUnit,
          id,
          productId
        });
      });
      let formData = {
        status: this.approveStatus,
        id: this.applyId,
        approveComments: this.form.getFieldValue("note"),
        itemList,
      };
      this.form.validateFields((err, values) => {
        if (!err) {
          postAction(this.url.approve, formData)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message);
                this.$emit("ok");
              } else {
                this.$message.warning(res.message);
              }
            })
            .finally(() => {
              this.confirmLoading = false;
              this.close();
            });
        }
      });
      this.confirmLoading = false;
    },
    handleCancel() {
      this.close();
    },
    handleWarehouseFlag(e) {
      this.model.channelFlag = e;
    },
    onChangeSkuUnit(event, row) {
      // if(event===""  || event==null){
      //   return;
      // }
      // if(parseInt(row.minUnitQuantity/row.productSkuSpec)<event) {
      //   return;
      // }
      // //如果物流实收（零散）+物流实收（整箱）> minUnitQuantity 则不允许填写
      // if(event==parseInt(row.minUnitQuantity/row.productSkuSpec) &&  row.minUnitQuantity%row.productSkuSpec<row.returnUnitCountNotUnit){
      //   return;
      // }
      row.returnSkuUnitCountNotUnit = event;
    },
    onChangeUnit(event, row) {
      // if(event===""  || event==null){
      //   return;
      // }
      // if(row.minUnitQuantity==0 && row.minUnitQuantity%row.productSkuSpec<event) {
      //   return;
      // }
      // if(row.productSkuSpec<event) {
      //   return;
      // }
      // //如果物流实收（零散）+物流实收（整箱）> minUnitQuantity 则不允许填写
      // if(row.returnSkuUnitCountNotUnit==parseInt(row.minUnitQuantity/row.productSkuSpec)  &&  row.minUnitQuantity%row.productSkuSpec<event){
      //   return;
      // }
      row.returnUnitCountNotUnit = event;
    },
  },
};
</script>
<style>

.title {
  margin-bottom: 10px;
  font-weight: bold;
  line-height: 1.5;
}
</style>